
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

[assembly: WebResource("Syrinx.Gui.AspNet.calRes.js.calendar_stripped.js", "application/x-javascript")]
[assembly: WebResource("Syrinx.Gui.AspNet.calRes.js.calendar-setup_stripped.js", "application/x-javascript")]
[assembly: WebResource("Syrinx.Gui.AspNet.calRes.js.calendar-loader.js", "application/x-javascript")]

[assembly: WebResource("Syrinx.Gui.AspNet.calRes.css.calendar-blue.css", "text/css")]
[assembly: WebResource("Syrinx.Gui.AspNet.calRes.css.calendar-blue2.css", "text/css")]
[assembly: WebResource("Syrinx.Gui.AspNet.calRes.css.calendar-brown.css", "text/css")]
[assembly: WebResource("Syrinx.Gui.AspNet.calRes.css.calendar-green.css", "text/css")]
[assembly: WebResource("Syrinx.Gui.AspNet.calRes.css.calendar-system.css", "text/css")]
[assembly: WebResource("Syrinx.Gui.AspNet.calRes.css.calendar-tas.css", "text/css")]
[assembly: WebResource("Syrinx.Gui.AspNet.calRes.css.calendar-win2k-1.css", "text/css")]
[assembly: WebResource("Syrinx.Gui.AspNet.calRes.css.calendar-win2k-2.css", "text/css")]
[assembly: WebResource("Syrinx.Gui.AspNet.calRes.css.calendar-win2k-cold-1.css", "text/css")]
[assembly: WebResource("Syrinx.Gui.AspNet.calRes.css.calendar-win2k-cold-2.css", "text/css")]

[assembly: WebResource("Syrinx.Gui.AspNet.calRes.lang.calendar-en.js", "application/x-javascript")]
namespace Syrinx.Gui.AspNet
{
	[Themeable(true)]
	[ToolboxData("<{0}:DropDownCalendar runat=server></{0}:DropDownCalendar>")]
	[ValidationProperty("Text")]
	public class DropDownCalendar : WebControl, IPostBackEventHandler
	{
		protected static string s_baseCssInfo = "Syrinx.Gui.AspNet.calRes.css.calendar-{0}.css";
		protected static string s_baseLangFileName = "Syrinx.Gui.AspNet.calRes.lang.calendar-{0}.js";

		protected string m_styleClassName = "win2k-1";
		protected string m_textFldClassName = null;
		protected string m_buttonClassName = "dropDownButton";
		protected string m_langOption = "en";
		protected string m_displayValue = "";
		protected string m_buttonTxt = "...";
		protected string m_dateDisplayFormat = "%m/%d/%Y";
		protected string m_timeDisplayFormat = "%H:%M";
		protected bool m_includeTime = true;
		protected int m_timeFormat = 12; //choice is 12 or 24.
		protected int m_firstDayOfWeek = 0;
		protected bool m_autoPostback = true;
		protected string m_clientOnChange = null;

		public string ClientOnChange
		{
			get { return m_clientOnChange; }
			set { m_clientOnChange = value; }
		}

		[Category("Appearance")]
		public string StyleClassName
		{
			get { return m_styleClassName; }
			set { m_styleClassName = value; }
		}

		[Category("Appearance")]
		public string ButtonClassName
		{
			get { return m_buttonClassName; }
			set { m_buttonClassName = value; }
		}

		[Category("Appearance")]
		public string TextFieldClassName
		{
			get { return m_textFldClassName; }
			set { m_textFldClassName = value; }
		}

		[Category("Appearance")]
		public string Language
		{
			get { return m_langOption; }
			set { m_langOption = value; }
		}

		[Category("Appearance")]
		public string ButtonText
		{
			get { return m_buttonTxt; }
			set { m_buttonTxt = value; }
		}

		[Category("Format")]
		public string DateDisplayFormat
		{
			get { return m_dateDisplayFormat; }
			set { m_dateDisplayFormat = value; }
		}

		[Category("Format")]
		public string TimeDisplayFormat
		{
			get { return m_timeDisplayFormat; }
			set { m_timeDisplayFormat = value; }
		}

		[Category("Format")]
		public bool IncludeTime
		{
			get { return m_includeTime; }
			set { m_includeTime = value; }
		}

		[Category("Appearance")]
		public bool UseMilitaryTime
		{
			get { return m_timeFormat == 12; }
			set
			{
				m_timeFormat = (value == true)?24:12;
			}
		}

		[Editor("System.ComponentModel.Design.DateTimeEditor, System.Design",
	typeof(System.Drawing.Design.UITypeEditor))]
		public DateTime TheDateTime { get { return DateTime.Now; } set { } }


		[Category("Data")]
		public string Text
		{
			get 
            {
                if (Page.IsPostBack)
                {
                    m_displayValue = Page.Request.Form[TxtFldId];
                    object fdw = ViewState["fdw"];
                    if (fdw is int)
                        m_firstDayOfWeek = (int)fdw;
                }
                else
                    ViewState["fdw"] = m_firstDayOfWeek;

                return m_displayValue; 
            }
			set { m_displayValue = value; }
		}
		
		[Category("Appearance")]
		public int FirstDayOfWeek
		{
			get { return m_firstDayOfWeek; }
			set { m_firstDayOfWeek = value; }
		}

		[Category("Behavior")]
		public bool AutoPostback
		{
			get { return m_autoPostback; }
			set { m_autoPostback = value; }
		}

		protected override void OnLoad(EventArgs e)
		{
			if (!Page.ClientScript.IsClientScriptIncludeRegistered("DropDownCalBase"))
			{
				string scriptUrl = Page.ClientScript.GetWebResourceUrl(typeof(DropDownCalendar), "Syrinx.Gui.AspNet.calRes.js.calendar_stripped.js");
				Page.ClientScript.RegisterClientScriptInclude("DropDownCalBase", scriptUrl);

				scriptUrl = Page.ClientScript.GetWebResourceUrl(typeof(DropDownCalendar), "Syrinx.Gui.AspNet.calRes.js.calendar-setup_stripped.js");
				Page.ClientScript.RegisterClientScriptInclude("DropDownCalSetup", scriptUrl);

				scriptUrl = Page.ClientScript.GetWebResourceUrl(typeof(DropDownCalendar), string.Format(s_baseCssInfo, m_styleClassName));
				string csslink = "<link href='" + scriptUrl + "' rel='stylesheet' type='text/css' />";
				LiteralControl include = new LiteralControl(csslink);
				this.Page.Header.Controls.Add(include);

				scriptUrl = Page.ClientScript.GetWebResourceUrl(typeof(DropDownCalendar), String.Format(s_baseLangFileName, m_langOption));
				Page.ClientScript.RegisterClientScriptInclude("DropDownCalLang", scriptUrl);
			}
			StringBuilder buff2 = new StringBuilder(4000);
			buff2.Append(readResFile("calRes.js.calendar-loader.js").Replace("$BaseName$", this.ID).Replace("$PostBackName$", this.ClientID));
			Page.ClientScript.RegisterClientScriptBlock(typeof(DropDownCalendar), this.UniqueID, buff2.ToString(), true);

			if (!Page.IsPostBack && Swaf.Application.currentApp.sessionData.get("LOG_DATE") != null && Swaf.Cmn.IsEmpty(this.Text))
				this.Text = Swaf.Application.currentApp.sessionData.get("LOG_DATE").ToString();
			else
			{
				if (Swaf.Cmn.IsEmpty(this.Text))
					this.Text = DateTime.Now.ToShortDateString();
				Swaf.Application.currentApp.sessionData.put("LOG_DATE", this.Text);
			}
			base.OnLoad(e);
		}

		protected string readResFile(string name)
		{
			name = typeof(DropDownCalendar).Namespace + "." + name;
			StreamReader resIn = new StreamReader(typeof(DropDownCalendar).Assembly.GetManifestResourceStream(name));
			string f = resIn.ReadToEnd();
			resIn.Close();
			return f;
		}

		protected string TxtFldId 
		{
			get
			{
				StringBuilder buff = new StringBuilder(100);
				buff.Append(ClientID).Append("Fld");
				return buff.ToString();
			}
		}
		protected string BtnFldId
		{
			get
			{
				StringBuilder buff = new StringBuilder(100);
				buff.Append(ClientID).Append("Btn");
				return buff.ToString();
			}
		}
		protected string getDesiredCss()
		{
			string resourceName = typeof(DropDownCalendar).Namespace + "." + String.Format(s_baseCssInfo, m_styleClassName);
			StreamReader cssIn = new StreamReader(typeof(DropDownCalendar).Assembly.GetManifestResourceStream(resourceName));
			StringBuilder buff = new StringBuilder(5000);
			buff.Append("<style type='text/css'>");
			buff.Append(cssIn.ReadToEnd());
			buff.Append("</style>");
			cssIn.Close();
			
			return buff.ToString();
		}

		protected static string s_baseHtml =
@"<input type='text' id='{0}' name='{1}' value='{2}' onblur='{13}calLostFocus()' {11}/><input id='{3}' {12} type='button' value='{4}'/>
<SCRIPT>
function {13}setup(){{
try{{
Calendar.setup({{inputField: '{0}', ifFormat: '{5}', firstDay: {8}, align: 'BL', button: '{3}', showsTime: {6}, timeFormat: '{7}', onUpdate: {13}dateSelected}});
}}catch(e){{setTimeout('{13}setup()',200);}}
}}
var {9}Origional = '{2}';
var {9}AutoPost = {10};
{13}setup();
</SCRIPT>";
		protected override void RenderContents(HtmlTextWriter output)
		{
			string extraAttribs = (m_textFldClassName == null ? "" : string.Format("class='{0}'", m_textFldClassName));
			if(ClientOnChange != null)
				extraAttribs = string.Format("{1} onchange='{0}'",ClientOnChange,extraAttribs);
			string html = String.Format(s_baseHtml,
				TxtFldId, //0
				TxtFldId, //1
				m_displayValue, //2
				BtnFldId, //3
				m_buttonTxt, //4
				m_dateDisplayFormat + (m_includeTime?(" " + m_timeDisplayFormat):""), //5
				m_includeTime.ToString().ToLower(), //6
				m_timeFormat, //7
				m_firstDayOfWeek, //8
				this.ID, //9
				m_autoPostback.ToString().ToLower(), //10
				extraAttribs, //11
				m_buttonClassName == null ? "" : string.Format("class='{0}'", m_buttonClassName), //12
				ClientID); //13
			output.Write(html);
		}

		#region IPostBackEventHandler Members

		public void RaisePostBackEvent(string eventArgument)
		{
			string[] args = eventArgument.Split('#');
			try
			{
				if (args.Length > 0)
				{
					if (args.Length == 4)
					{
						m_firstDayOfWeek = Int32.Parse(args[1]);

						ViewState["fdw"] = m_firstDayOfWeek;
					}
				}
			}
			catch { }

		}

		#endregion
	}
}
